
#import "PaymentObject.h"
#import <AlipaySDK/AlipaySDK.h>
#import "NetWorkRequest.h"
#import <WXApi.h>
#import <UPPaymentControl.h>

static PaymentObject * pay = nil;
@implementation PaymentObject

+ (PaymentObject *)sharePayMange {
    if (!pay) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{ 
            pay = [[self alloc] init];
        });
    }
    return pay;
}

- (void)paymentStringFormatting:(NSString *)orderString {
    
    //    haleyaction://pay_event?
    //type=1&
//    amount=101&
//    orderNum=B17112915081160&
//rurl=%2fmall%2forder%2fpaysuccess%3fwid%3d7%26dealerid%3d10005%26id%3d252%26uatphone%3d3B08F77717D4479BEC14009668BB81F6
    NSString * url = @"";
    NSDictionary * originalDic = [self cutStrToDic:orderString];//包含所有信息
    NSDictionary * idDic = [self cutStrToDic:[self URLDecodedString:[originalDic objectForKey:@"rurl"]]];
    NSString *weixinPayUrl = @"/api/WxPay/GetWxOrder/GetWxOrder";
    NSString *zhifubaoPayUrl = @"/api/WxPay/GetAliPay";
    //1微信 2支付宝
    BOOL whetheWX = [[originalDic objectForKey:@"type"] isEqualToString:@"1"];
    
    if (whetheWX) {
        if (![WXApi isWXAppInstalled]) {
            //判断是否有微信
            [[BONoticeBar defaultBar] setNoticeText:@"您未安装微信"];
            return;
        } 
    }
    
    if (whetheWX) {
        url = weixinPayUrl;
    } else {
        url = zhifubaoPayUrl;
    }
    
    //此处用获取字典的方法 objectForKey 时出现无名问题，在iPhone7突然中止流程，不显示崩溃，没有日志，其他手机没问题，暂时用最简单的方法写出来
//    float amount = [[originalDic objectForKey:@"amount"] floatValue] / 100;
//    NSString * total_fee = [NSString stringWithFormat:@"%.2f",amount];
    NSString * total_fee = [originalDic objectForKey:@"amount"];
    NSString * orderNum = [NSString stringWithFormat:@"%@",originalDic[@"orderNum"]];
    NSString * wid = [NSString stringWithFormat:@"%@",idDic[@"wid"]];
    NSString * idN = [NSString stringWithFormat:@"%@",idDic[@"id"]];
    
    NSDictionary * parmentDic = @{@"out_trade_no":orderNum,
                                  @"total_fee":total_fee,
                                  @"storeId":wid,
                                  @"orderId":idN,
                                  };
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest getNetRequestData:url parmeters:parmentDic response:^(NSDictionary *response) {
        //微信
        if (whetheWX) {
            [weakSelf wxPayAcion:response[@"Content"]];
            //支付宝
        } else {
            [weakSelf alipayAction:response[@"Content"]];
        }
//        tn 是交易流水号，fromScheme 是商户自定义协议， mode 是接入模式，viewController指的是发起调用的视图控制器。
//        mode 是个死的字符串 "00"表示线上环境"01"表示测试环境
//        返回的代理结果 :success、fail、cancel,分别代表:支付成功、支付失败、用户取消支付
//        [[UPPaymentControl defaultControl] startPay:@"加签" fromScheme:@"UPPay" mode:@"00" viewController:self];
        //当获得的tn不为空时，调用支付接口
//        if (tn != nil && tn.length > 0)
//        {
//            [[UPPaymentControl defaultControl]
//             startPay:tn
//             fromScheme:@"UPPay"
//             mode:self.tnMode
//             viewController:self];
//        }
        
        
    } netError:^(NSError *error) {
        
    }];
}

//字符串剪切之后生成需要的字典
- (NSDictionary *)cutStrToDic:(NSString *)dicStr {
    NSMutableDictionary * mutableDic = [NSMutableDictionary dictionaryWithCapacity:10];
    NSString * parmentStr = [dicStr componentsSeparatedByString:@"?"].lastObject;
    NSArray * parmentArray = [parmentStr componentsSeparatedByString:@"&"];
    for (int i = 0; i < parmentArray.count; i++) {
        NSString * tmpStr = parmentArray[i];
        NSArray * tmpArray = [tmpStr componentsSeparatedByString:@"="];
        [mutableDic setObject:tmpArray[1] forKey:tmpArray[0]];
    }
    return mutableDic;
}

//支付宝付款
- (void)alipayAction:(NSString *)orderString {
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:alipayUrl callback:^(NSDictionary *resultDic) {
        NSLog(@"%@",resultDic);
    }];
}

- (void)wxPayAcion:(NSDictionary *)dic {
    
    if (![WXApi isWXAppInstalled]) {
        //判断是否有微信
        [[BONoticeBar defaultBar] setNoticeText:@"您未安装微信"];
        return;
    } 
    
    PayReq * request = [[PayReq alloc] init];
    request.partnerId = [dic objectForKey:@"partnerid"];
    request.prepayId = [dic objectForKey:@"prepayid"];
    request.package = @"Sign=WXPay";
    request.nonceStr= [dic objectForKey:@"noncestr"];
    request.timeStamp = [[dic objectForKey:@"timestamp"] intValue];
    request.sign= [dic objectForKey:@"sign"];
    [WXApi sendReq:request];
}

#pragma mark - decode
//解密
-(NSString *)URLDecodedString:(NSString *)str {
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

//加密
-(NSString *)URLEncodedString:(NSString *)str
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

@end
